from time import mktime,strptime
from xml import sax

class GPXreader:



  class Trkseg: # for GPX <trkseg> tags
    def __init__(self, points=None):
      self.name = None
      self.points = points or []
      self.cliques = []
      self.profile_image = None
      
    def __len__(self):
      return len(self.points)
    def __getitem__(self, i):
      return self.points[i]
    def parseCliques(self, txt):
      self.cliques = txt[1:-1].split(',')
      self.cliques = [ int(x) for x in self.cliques ] 
      #print self.cliques

  class Trkpt: # for GPX <trkpt> tags
    def __init__(self, lat, lon):
      self.lat = float(lat)
      self.lon = float(lon)
      self.time = None
      self.text = None
    def __str__(self):
      return '[%f,%f] t=%s' % (self.lat, self.lon, self.time)

  class _ParseHandler(sax.ContentHandler):

    def __init__(self):
      self.html_escape_table = { 
           "&": "&amp;",
           '"': "&quot;",
           "'": "&apos;",
           ">": "&gt;",
           "<": "&lt;",
           "\\": "\\\\",
           "\n": ""
       }
     
    def html_escape(self,text):
      """Produce entities within text."""
      s = ""
      for c in text:
        try:
          s += self.html_escape_table[c]
        except KeyError:
          s += c
      return s

    def startDocument(self):
      self.tag_name_stack = []
      self.points = []
      self.segments = []

    def startElement(self, name, attrs):
      self.content = ''
      self.tag_name_stack.append(name)
      if name == 'trkpt':
        self.points.append(GPXreader.Trkpt(attrs['lat'], attrs['lon']))
        self.segments[-1].points.append(self.points[-1])
        
      elif name == 'trkseg':
        newSeg = GPXreader.Trkseg()
        newSeg.name = attrs['name']
        self.segments.append(newSeg)
        newSeg.parseCliques(attrs['cliques'])
        newSeg.profile_image = attrs['profile_image']

    def endElement(self, name):
      if self.content:
        if self.tag_name_stack[-1] == 'time' and self.tag_name_stack[-2] == 'trkpt':
          self.points[-1].time = int(mktime(strptime(self.content, "%a, %d %b %Y %H:%M:%S +0000")))-5*3600
          self.segments[-1].points[-1].time = self.points[-1].time
        if self.tag_name_stack[-1] == 'tweet' and self.tag_name_stack[-2] == 'trkpt':
          self.points[-1].text = self.html_escape(self.content).encode("utf-8")
          self.segments[-1].points[-1].text = self.points[-1].text
      self.tag_name_stack.pop()
        
    def characters(self, content):
      self.content += content

  def __init__(self, filename):
    handler = GPXreader._ParseHandler()
    parser = sax.make_parser()
    parser.setContentHandler(handler)
    parser.parse(filename)
    self.points = handler.points
    self.segments = handler.segments

  def __len__(self):
    return len(self.points)
  def __getitem__(self, i):
    return self.points[i]

  def getData(self):
    SegmentToPoints = {}
    SegmentToCliques = {}
    SegmentToFriends = {}
    SegmentToImage = {}
    for s in self.segments:
      SegmentToPoints[s.name] = []
      for p in s.points:
        SegmentToPoints[s.name].append( [p.lon, p.lat, p.time, p.text] )
      SegmentToCliques[s.name] = s.cliques
      SegmentToImage[s.name] = s.profile_image
      # read off cliques
    for u1 in SegmentToCliques.keys():
      for u2 in SegmentToCliques.keys():
        #if u2 >= u1:
        #  continue
        c1 = SegmentToCliques[u1]
        c2 = SegmentToCliques[u2]
        intersection = [n for n in c1 if n in c2]
        if len(intersection) > 0:
          try:
            SegmentToFriends[u1].append(u2)
          except KeyError:
            SegmentToFriends[u1] = [u2]
          
    print SegmentToFriends
    return (SegmentToPoints, SegmentToCliques, SegmentToFriends, SegmentToImage)

  def printPoints(self):
    for p in self.points:
      print p


    
